var AddThis_Preferences = {
    
    initPreferences: function()
    {
        AddThis_Util.dbg("initPreferences: go...");
        
        this.browserWindow = this._getBrowser();
        AddThis_Preferences._initServicePreferences();
        AddThis_Preferences._initDisplayPreferences();
        
        if (AddThis_Preferences.isSearchPartner()) {
            AddThis_Preferences.hideSearchOption();
        } else {
            AddThis_Preferences.setAddThisSearchButton();
        }
        
        AddThis_Util.dbg("initPreferences: done");
    
    },
    
    _initServicePreferences: function()
    {
        AddThis_Util.dbg("_initServicePreferences");
        
        var allcontainer = document.getElementById("at_prefs_list_all"),
            activecontainer = document.getElementById("at_prefs_list_active"),
            activeServices = AddThis_Util.getActiveServicesObject();
        
        var serviceId, newItem;
        
        
        while(allcontainer.firstChild) allcontainer.removeChild(allcontainer.firstChild);
        while(activecontainer.firstChild) activecontainer.removeChild(activecontainer.firstChild);
        
        for(serviceId in AddThis_Constants.services)
        {
            if (typeof activeServices[serviceId] !== "undefined" && activeServices[serviceId] === true) {
                continue;
            }
            
            
            newItem = document.createElement("listitem");
            newItem.setAttribute("serviceid",serviceId);
            newItem.setAttribute("class","listitem-iconic");
            newItem.setAttribute("label", AddThis_Constants.services[serviceId].title);
            newItem.setAttribute("image","chrome://addthis/skin/services/"+serviceId+".gif");
            
            allcontainer.appendChild(newItem);
        }
        
        for(serviceId in activeServices)
        {
            
            newItem = document.createElement("listitem");
            newItem.setAttribute("serviceid",serviceId);
            newItem.setAttribute("class","listitem-iconic");
            newItem.setAttribute("label", AddThis_Constants.services[serviceId].title);
            newItem.setAttribute("image","chrome://addthis/skin/services/"+serviceId+".gif");
            
            activecontainer.appendChild(newItem);
        }
    },
    
    _initDisplayPreferences: function()
    {
        AddThis_Util.dbg("_initDisplayPreferences");
        
        var cbxUrlbar = document.getElementById("at_prefs_showurlbar");
        cbxUrlbar.checked = AddThis_UrlBar.isVisible(this.browserWindow.document);
        var cbxToolbar = document.getElementById("at_prefs_showtoolbar");
        cbxToolbar.checked = AddThis_Toolbar.isVisible(this.browserWindow.document);
        var cbxButton = document.getElementById("at_prefs_showbutton");
        cbxButton.checked = AddThis_MainButton.isVisible(this.browserWindow.document);
        var radToolbarStyle = document.getElementById("at_prefs_toolbarstyle"),
            tbs = AddThis_Util.getStringPref('extensions.addthis.toolbar.buttonstyle', "icons");
        radToolbarStyle.selectedIndex = (tbs == "text" ? 1 : (tbs == "full" ? 2 : 0));
    },
    
    _getBrowser: function()
    {
        var b = (opener == null) ? false : AddThis_Preferences._checkOpenersForBrowser(opener);
        if (b === false)
        {
            
            b = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Components.interfaces.nsIWindowMediator)
                   .getMostRecentWindow("navigator:browser");
        }
        return b;
	},
    
    _checkOpenersForBrowser: function(win)
    {
        if (win.location.href.indexOf("browser.xul") !== -1)
        {
            return win;
        }
        else if (win.opener != null)
        {
            return this._checkOpenersForBrowser(win.opener);
        }
        else
        {
            return false;
        }
        
    },

    updateServicePrefs: function()
    {
        AddThis_Util.dbg('updateServicePrefs: updating...');
        
        var l = document.getElementById('at_prefs_list_active');
           
        var i, services = [];
        for(i=0; i < l.childNodes.length; i++)
        {
            services.push(l.childNodes[i].getAttribute('serviceid'));
        }
        
        var serviceInclude = services.join(',');
        AddThis_Util.setStringPref('extensions.addthis.service.personal', serviceInclude);
        AddThis_Util.dbg('...' + serviceInclude);
        this.browserWindow.AddThis_Toolbar.setServices();

        
    },
    
    resetServicePrefs: function()
    {
        var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                                .getService(Components.interfaces.nsIPromptService);
        
        if(prompts.confirm(window,"","Are you sure you want to restore the default list of services? Any additional services you selected will be removed."))
        {
            AddThis_Util.loadServiceDefaults();
            AddThis_Preferences._initServicePreferences();
            this.browserWindow.AddThis_Toolbar.setServices();

        }
        
    },
    
    updateToolbarPref: function()
    {
        var t = document.getElementById('at_prefs_showtoolbar');
        AddThis_Toolbar.setVisibility(t.checked,this.browserWindow.document);
    },
    
    updateToolbarButtonStylePref: function()
    {
        var i = document.getElementById('at_prefs_toolbarstyle');
        AddThis_Util.setStringPref('extensions.addthis.toolbar.buttonstyle', i.selectedItem.value);
        this.browserWindow.AddThis_Toolbar.setButtonStyle();

    },
    
    updateButtonPref: function()
    {
        var b = document.getElementById('at_prefs_showbutton');
        AddThis_MainButton.setVisibility(b.checked,this.browserWindow.document);
        window.focus(); 
    },
    
    updateUrlbarPref: function()
    {
        var t = document.getElementById('at_prefs_showurlbar');
        AddThis_Util.setBooleanPref('extensions.addthis.urlbar.disable',!t.checked);
        AddThis_UrlBar.setVisibility(t.checked,this.browserWindow.document);
    },
    
    setDefaultSearch: function()
    {
        AddThis_Util.setStringPref("browser.search.defaultenginename", AddThis_Constants.SEARCH_PLUGIN);
        AddThis_Util.setStringPref("keyword.URL", AddThis_Search.getUrl('ub'));
        
    },
    
    resetDefaultSearch: function()
    {
        AddThis_Util.clearPref("browser.search.defaultenginename");
        AddThis_Util.clearPref("keyword.URL");
    },
    
    allListSelect: function()
    {
        var a = document.getElementById('btnAdd'),
            l = document.getElementById('at_prefs_list_all');
        a.disabled = (l.selectedCount == 0);
    },
    
    isSearchPartner: function()
    {
        var domain = "search.yahoo.com";
        return (AddThis_Util.getStringPref("keyword.URL","").indexOf(domain) > 0);
    },
    
    hideSearchOption: function()
    {
        var e = document.getElementById("at_prefs_search_container");
        e.hidden = true;
    },
    
    setAddThisSearchButton: function(disable)
    {
        if (typeof disable == 'undefined')
        {
            disable = AddThis_Search.isVisible();
        }
        else disable = (disable === true);
        var b = document.getElementById('at_prefs_search_addthis');
        b.disabled = disable;

    },
    
    activeListSelect: function()
    {
        var r = document.getElementById('btnRemove'),
            u = document.getElementById('btnUp'),
            d = document.getElementById('btnDown'),
            l = document.getElementById('at_prefs_list_active');
        
        if (l.selectedCount == 0) {
                u.disabled = d.disabled = r.disabled = true;
        } else if (l.selectedCount == 1) {
                u.disabled = (l.selectedIndex == 0);
                d.disabled = (l.selectedIndex == l.childNodes.length - 1);
                r.disabled = false;
        } else {
                u.disabled = d.disabled = true;
                r.disabled = false;
        }
    },
    
    addService: function()
    {
        var ll = document.getElementById('at_prefs_list_all'),
            lc = document.getElementById('at_prefs_list_active');
            
        var li;
        while(ll.selectedItems.length > 0)
        {
            li = ll.selectedItems[0];
            ll.removeChild(li);
            lc.appendChild(li);
        }
        
        AddThis_Preferences.updateServicePrefs();
    },
    
    removeService: function()
    {
        
        var ll = document.getElementById('at_prefs_list_all'),
            lc = document.getElementById('at_prefs_list_active');
            
        var li;
        while(lc.selectedItems.length > 0)
        {
            li = lc.selectedItems[0];
            lc.removeChild(li);
            ll.appendChild(li);
        }
        
        AddThis_Preferences._sortList(ll);
        
        AddThis_Preferences.updateServicePrefs();
    },
    
    moveServiceUp: function()
    {
        var l = document.getElementById('at_prefs_list_active'),
            i = l.selectedItem,
            pi = i.previousSibling;
        l.insertBefore(i,pi);
        l.selectedItem = i;
        
        AddThis_Preferences.updateServicePrefs();
    },
    
    moveServiceDown: function()
    {
        var l = document.getElementById('at_prefs_list_active'),
            i = l.selectedItem,
            ni = i.nextSibling;
        l.insertBefore(i,ni.nextSibling);
        l.selectedItem = i;
        
        AddThis_Preferences.updateServicePrefs();
    },
    
    filterServices: function(event)
    {
        var la = document.getElementById('at_prefs_list_all'),
            lh = document.getElementById('at_prefs_list_hidden'),
            fname = document.getElementById('at_prefs_filtername'),
            fcat = document.getElementById('at_prefs_filtercat_menu'),
            nam = fname.value.toLowerCase();
            
        
        var cat = "", i,
            mi = fcat.getElementsByTagName('menuitem');
        for(i=0;i<mi.length;i++)
        {
            if(mi[i].hasAttribute('checked'))
            {
                cat = mi[i].value;
                break;
            }
        }
        
        
        while(lh.firstChild)
        {
            la.appendChild(lh.removeChild(lh.firstChild));
        }
        
        var resetNam = (nam=="") , resetCat = (cat=="");
        var li, ls, lv, hide;
        for(i=0;i<la.childNodes.length;i++)
        {
            li = la.childNodes[i];
            serviceid = li.getAttribute('serviceid');
            label = li.getAttribute('label').toLowerCase();
            if ((!resetCat && AddThis_Constants.services[serviceid].cat != cat) ||
                (!resetNam && serviceid.indexOf(nam)==-1 && label.indexOf(nam)==-1))
            {
                lh.appendChild(la.removeChild(li));
                i--; 
            }
        }
        
        AddThis_Preferences._sortList(la);
       
    },
    
    blurList: function(d)
    {
        var l = document.getElementById('at_prefs_list_'+d);
        l.selectedIndex = -1;
    },
    
    _sortList: function(l) {
        var nodes = [];
        while(l.firstChild)
        {
            nodes.push(l.removeChild(l.firstChild));
        }
        
        nodes.sort(AddThis_Preferences._sortli);
        
        var i;
        for(i=0;i<nodes.length;i++)
        {
            l.appendChild(nodes[i]);
        }
    },
    
    _sortli: function(a,b)
    {
        var aa = a.getAttribute('label').toLowerCase(),
            bb = b.getAttribute('label').toLowerCase();
        return (aa==bb) ? 0 : (aa < bb ? -1 : 1);
    },
    
    initWelcome: function()
    {

        this.browserWindow = this._getBrowser();
        
        if (AddThis_Preferences.isSearchPartner()) AddThis_Preferences.hideSearchOption();
        
        var ww = document.getElementById("lightbox").boxObject.width;
        var d = document.getElementById("overlay");
        d.left = (ww - d.boxObject.width) / 2;
        
        if (AddThis_Util.fxVersionAtLeast("3.0a"))
        {
            document.getElementById("frame").style.visibility = "visible";
            document.getElementById("lightbox").style.visibility = "visible";
        }
        else
        {
            document.getElementById("finish-button").id = ""; 
        }
        document.getElementById("overlay").style.visibility = "visible";
        document.getElementById("frame").setAttribute("src",AddThis_Constants.WELCOME_URL);
    },
    
    processWelcome: function()
    {
        if (!AddThis_Preferences.isSearchPartner())
        {
            var cbxSearch = document.getElementById("at_prefs_search");
            if (cbxSearch.checked) AddThis_Preferences.setDefaultSearch();
        }
        
        var cbxHide = document.getElementById("at_prefs_hidetoolbars");
        if (cbxHide.checked)
        {
            var doc = this.browserWindow.document;
            var toolbox = doc.getElementById("navigator-toolbox");
            var toolbars = toolbox.getElementsByTagName("toolbar");
            var tb,z="";
            for(var i in toolbars)
            {
                tb = toolbars[i];
                if (tb.id && tb.id != "toolbar-menubar" && tb.id != "nav-bar" && tb.id != "PersonalToolbar" && tb.id != "TabsToolbar"  && tb.id != "at_toolbar")
                {
                    if (!(tb.collapsed || tb.hidden || getComputedStyle(tb,null).getPropertyValue('display')=='none'))
                    {
                        tb.collapsed = true;
                        doc.persist(tb.id, "collapsed");
                    }
                }
            }
        }
        
        if (!AddThis_Util.fxVersionAtLeast("3.0a"))
        {
            document.getElementById("frame").style.visibility = "visible";
        }
        else
        {
            document.getElementById("lightbox").style.display = "none";
        }
        document.getElementById("overlay").style.display = "none";
        
        return true;
    }

};